<?php

declare(strict_types=1);
/**
 *  +----------------------------------------------------------------------
 *  | 陀螺匠 [ 赋能开发者，助力企业发展 ]
 *  +----------------------------------------------------------------------
 *  | Copyright (c) 2016~2024 https://www.tuoluojiang.com All rights reserved.
 *  +----------------------------------------------------------------------
 *  | Licensed 陀螺匠并不是自由软件，未经许可不能去掉陀螺匠相关版权
 *  +----------------------------------------------------------------------
 *  | Author: 陀螺匠 Team <admin@tuoluojiang.com>
 *  +----------------------------------------------------------------------
 */

namespace App\Http\Model\Storage;

use App\Http\Model\BaseModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Cache;

/**
 * 物资分类.
 *
 * Class StorageCategory.
 */
class StorageCategory extends BaseModel
{
    protected $primaryKey = 'id';

    protected $table = 'storage_category';

    /**
     * path修改器.
     */
    public function setPathAttribute($value)
    {
        $this->attributes['path'] = $value ? implode('/', $value) : '';
    }

    /**
     * path获取器.
     * @return false|string[]
     */
    public function getPathAttribute($value)
    {
        return $value ? array_map('intval', explode('/', $value)) : [];
    }

    /**
     * 分类类型作用域
     * @param Builder $query
     * @return Builder
     */
    public function scopeType($query, $value)
    {
        return $query->where('type', $value);
    }

    /**
     * 企业ID作用域
     * @param Builder $query
     * @return Builder
     */
    public function scopeEntid($query, $value)
    {
        if ($value !== '') {
            $query->where('entid', $value);
        }
    }

    /**
     * 企业ID作用域
     * @param Builder $query
     * @return Builder
     */
    public function scopeNameLike($query, $value)
    {
        return $value !== '' ? $query->where('cate_name', 'LIKE', "%{$value}%") : null;
    }

    /**
     * 作用域
     * @param Builder $query
     * @return Builder
     */
    public function scopeCateName($query, $value)
    {
        if ($value !== '') {
            $query->where('cate_name', $value);
        }
    }

    /**
     * 作用域
     * @param Builder $query
     * @return Builder
     */
    public function scopePid($query, $value)
    {
        if ($value !== '') {
            $query->where('pid', $value);
        }
    }

    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        static::saved(function ($data) {
            Cache::tags(['storage_cate_' . $data->entid, 'storage_record_list_' . $data->entid])->flush();
        });
    }
}
